package org.afi.mushroomplayer.utils;

import java.util.List;

import org.afi.mushroomplayer.model.SongInfo;

import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.AudioColumns;
import android.provider.MediaStore.MediaColumns;

public class MediaScanner {

	private Context mContext;
	private List<SongInfo> mSongList;

	public MediaScanner(Context context, List<SongInfo> list) {
		this.mSongList = list;
		this.mContext = context;
	}

	public List<SongInfo> scan() {
		mSongList.clear();

		Cursor cursor = mContext.getContentResolver().query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
				MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
		if (cursor.moveToFirst()) {
			while (!cursor.isAfterLast()) {
				long size = cursor.getLong(cursor
						.getColumnIndexOrThrow(MediaColumns.SIZE));
				if (size > 1024 * 500) {
					SongInfo mInfo = new SongInfo();
					String title = cursor.getString(cursor
							.getColumnIndexOrThrow(MediaColumns.TITLE));
					String album = cursor.getString(cursor
							.getColumnIndexOrThrow(AudioColumns.ALBUM));
					String artist = cursor.getString(cursor
							.getColumnIndexOrThrow(AudioColumns.ARTIST));
					String url = cursor.getString(cursor
							.getColumnIndexOrThrow(MediaColumns.DATA));
					int duration = cursor.getInt(cursor
							.getColumnIndexOrThrow(AudioColumns.DURATION));
					mInfo.setTitle(title);
					mInfo.setSize(BaseUtils.toSizeString(size));
					mInfo.setAlbum(album);
					mInfo.setArtist(artist);
					mInfo.setUrl(url);
					mInfo.setDuration(duration);
					mSongList.add(mInfo);
				}
				cursor.moveToNext();
			}
		}
		return mSongList;
	}

}
